package com.gnrsoft.rpc.registry;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;

/**
 * 
 * <B>中文类名：服务注册类</B><BR>
 * <B>概要说明：</B><BR>
 * @author likun
 * @since 2017年7月21日
 */
public class ServiceRegistry {

	private CountDownLatch countDownLatch = new CountDownLatch(1);

	private String registryAddress;

	public ServiceRegistry() {
	}

	public ServiceRegistry(String registryAddress) {

		this.registryAddress = registryAddress;

	}

	public void registry(String serverAddress) {
		if (serverAddress != null) {

			ZooKeeper zooKeeper = connectServer();
			if (zooKeeper != null) {
				createNode(zooKeeper, serverAddress);
			}

		}
	}

	private void createNode(ZooKeeper zooKeeper, String serverAddress) {
		try {

			byte[] data = serverAddress.getBytes();

			if (zooKeeper.exists(Constant.ZK_REGISTRY_PATH, null) == null) {
				zooKeeper.create(Constant.ZK_REGISTRY_PATH, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			}

			String path = zooKeeper.create(Constant.ZK_DATA_PATH, data, Ids.OPEN_ACL_UNSAFE,
					CreateMode.EPHEMERAL_SEQUENTIAL);

			System.out.println("create Zookeeper Node path = " + path + " data = " + serverAddress);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private ZooKeeper connectServer() {
		ZooKeeper zk = null;
		try {
			zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {

				@Override
				public void process(WatchedEvent event) {

					KeeperState ks = event.getState();
					EventType et = event.getType();
					if (ks.SyncConnected == ks) {
						if (EventType.None == et) {
							System.out.println("zookeeper connection scucess");
							countDownLatch.countDown();
						}
					}
				}
			});
			countDownLatch.await();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return zk;

	}

	public String getRegistryAddress() {
		return registryAddress;
	}

	public void setRegistryAddress(String registryAddress) {
		this.registryAddress = registryAddress;
	}

}
